'use strict';
const BaseController = require('./base');
const serviceName = 'idleTransfer';

class IdleTransferController extends BaseController {
  constructor(ctx) {
    super(ctx, serviceName);
  }

  getPageQuery(query) {
    const where = {};
    const { item_id, name, from_project_id, type, to_project_id, status, apply_user_id,approve_user_id } = query;

    if (item_id) {
      where.item_id = item_id;
    }
    if (from_project_id) {
      where.from_project_id = from_project_id;
    }
    if (to_project_id) {
      where.to_project_id = to_project_id;
    }
    if (status) {
      where.status = status;
    }
    if (apply_user_id) {
      where.apply_user_id = apply_user_id;
    }
    if (approve_user_id) {
      where.approve_user_id = approve_user_id
    }
    if (type) {
      where.type = type
    }
    if (name) {
      where.name = {
        [this.app.Sequelize.Op.like]: `%${name}%`,
      };
    }

    return where;
  }

  async apply() {
    const { ctx } = this;
    const data = ctx.request.body;
    data.status = 'pending';

    const result = await ctx.service[this.serviceName].apply(data);
    ctx.success(result);
  }

  async approve() {
    const { ctx } = this;
    const { id, status, remark, approved_user_id, approved_user_name } = ctx.request.body;

    if (!id) {
      ctx.throw(400, 'ID参数不能为空');
    }
    if (!['approved', 'rejected'].includes(status)) {
      ctx.throw(400, '状态参数错误');
    }

    const result = await ctx.service[this.serviceName].approve({
      id, status, remark, approved_user_id, approved_user_name
    });
    ctx.success(result);
  }

  async complete() {
    const { ctx } = this;
    const { id } = ctx.params;

    if (!id) {
      ctx.throw(400, 'ID参数不能为空');
    }

    const result = await ctx.service[this.serviceName].complete(id);
    ctx.success(result);
  }

  async cancel() {
    console.log('cancel')
    const { ctx } = this;
    const { id } = ctx.request.body;

    if (!id) {
      ctx.throw(400, 'ID参数不能为空');
    }

    const result = await ctx.service[this.serviceName].cancel(id);
    ctx.success(result);
  }

  async myApplies() {
    const { ctx } = this;
    const userId = ctx.query.user_id
    const result = await ctx.service[this.serviceName].getMyApplies(userId, ctx.query);
    ctx.success(result);
  }

  async myApprovals() {
    const { ctx } = this;
    const userId = ctx.state.user.id;
    const result = await ctx.service[this.serviceName].getMyApprovals(userId, ctx.query);
    ctx.success(result);
  }

  async statistics() {
    const { ctx } = this;
    const { startDate, endDate, create_user_id } = ctx.query;
    const result = await ctx.service[this.serviceName].getStatistics(startDate, endDate);
    ctx.success(result);
  }
}

module.exports = IdleTransferController;
